package com.liuyanzhao.ssm.blog.interceptor;

import com.liuyanzhao.ssm.blog.entity.User;
import com.liuyanzhao.ssm.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author liuyanzhao
 */
@Component
public class SecurityInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    public UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws IOException {
        //这里可以根据session的用户来判断角色的权限，根据权限来转发不同的页面
        if (request.getSession().getAttribute("user") != null) {
            return true;
        }

        String username = null;
        String password = null;

        Cookie [] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("username")) {
                username = cookie.getValue();

            } else if (cookie.getName().equals("password")) {
                password = cookie.getValue();
            }
        }

        if (username != null && password != null) {
            User user = userService.getUserByNameOrEmail(username);
            if(user.getUserPass().equals(password)){
                request.getSession().setAttribute("user", user);
                return true;
            }
        }

        response.sendRedirect("/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)  {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)  {

    }
}

